<template>
	<view class="uni-container">
		<view class="header">
			<view class="back">
				<view @click="navigateBack" style="margin-left: 15px;display: flex;align-items: center;color: #fff;">
					<uni-icons type="back" size="24" color="#fff"></uni-icons>
					<text>返回</text>
				</view>
			</view>
		</view>
		<!-- 媒体库弹窗 -->
		<uni-drawer class="insert-image-drawer" v-if="drawerWidth" ref="insertImageDrawer" mode="right"
			:width="drawerWidth">
			<uni-media-library mode="picker" :selected-count="1" :media-tabs="['image']"
				@onInsert="onInsertCover"></uni-media-library>
		</uni-drawer>
		<view class="w-100 flex-dir-col ali-item-cen">
			<uni-forms class="bac-col-f" ref="form" :model="formData" validateTrigger="bind">
				<uni-forms-item name="category_id" label="问题分类">
					<uni-data-picker v-model="formData.category_id" collection="opendb-news-categories"
						field="name as text, _id as value"></uni-data-picker>
				</uni-forms-item>
				<uni-forms-item name="title" label="问题标题">
					<uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="content" label="问题内容">
					<view style="border: 1rpx solid #F0F0F0;padding: 0 30rpx;">
						<editor-component @textchange="onTextChange" @ready="onEditorReady"></editor-component>
					</view>
					<!-- <uni-easyinput placeholder="问题内容" v-model="formData.content" trim="right"></uni-easyinput> -->
				</uni-forms-item>
				<uni-forms-item name="article_status" label="发布状态">
					<uni-data-checkbox v-model="formData.article_status"
						:localdata="formOptions.article_status_localdata"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item name="avatar" label="封面大图">
					<view style="display: flex;flex-direction: row;flex-wrap: wrap;">
						<view v-if="formData.avatar == ''" @click="openInsertImageDrawer()"
							style="width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;">
							<uni-icons class="placeholder" type="plusempty" size="60" color="#e8e8e8"></uni-icons>
						</view>
						<view v-else
							style="position: relative;width: 300rpx;height: 300rpx;border: 1rpx solid #F0F0F0;border-radius: 20rpx;text-align: center;line-height: 300rpx;margin-right: 30rpx;margin-bottom: 30rpx;">
							<view
								style="position: absolute;right: 10rpx;top: 10rpx;z-index: 1;background: #6666667d;border-radius: 200rpx;width: 50rpx;height: 50rpx;line-height: 50rpx;"
								@click="removeThumbnail()">
								<uni-icons type="closeempty" size="16" color="#ffffff"></uni-icons>
							</view>
							<image style="width: 150px;height: 150px;position: absolute;top:0;left: 0;" class="br-20"
								:src="formData.avatar">
							</image>
						</view>

					</view>
					<!-- <uni-easyinput placeholder="缩略图地址" v-model="formData.avatar" trim="both"></uni-easyinput> -->
				</uni-forms-item>
				<view class="uni-button-group">
					<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
					<navigator open-type="navigateBack" style="margin-left: 15px;">
						<button class="uni-button" style="width: 100px;">返回</button>
					</navigator>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/opendb-news-articles.js';
	// 引入编辑器组件
	import EditorComponent from "@/uni_modules/uni-cms/components/editor/editor.vue";

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'opendb-news-articles';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		components: {
			EditorComponent
		},
		data() {
			let formData = {
				"category_id": "",
				"title": "",
				"content": "",
				"article_status": 1,
				"avatar": ""
			}
			return {
				drawerWidth: 0,
				formData,
				formOptions: {
					"article_status_localdata": [{
							"value": 0,
							"text": "草稿箱"
						},
						{
							"value": 1,
							"text": "已发布"
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}

			}
		},
		mounted() {
			const sysinfo = uni.getSystemInfoSync()
			this.drawerWidth = sysinfo.windowWidth * .8
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			async onInsertCover(selectMediaItems) {
				if (selectMediaItems.length > 1) {
					return uni.showToast({
						title: '最多只能选择1张图片',
						icon: 'none'
					})
				} else {
					this.formData.avatar = selectMediaItems[0].src;
				}
				this.$refs.insertImageDrawer.close()
			},
			openInsertImageDrawer() {
				if (this.formData.avatar != "") {
					uni.showToast({
						title: '最多只能选择1张图片',
						icon: 'none',
						mask: true
					})
				} else {
					this.$refs.insertImageDrawer.open()
				}
			},
			removeThumbnail() {
				this.formData.avatar = ''; // 删除 index 位置的元素
				uni.showToast({
					title: '删除成功',
					icon: 'none'
				});
			},

			// 监听富文本编辑器内容变化
			onTextChange(e) {
				console.log(e)
				this.editorCtx.getContents({
					success: (e) => {
						this.formData.content = e.html
					}
				})
			},

			// 富文本编辑器初始化完成后触发
			onEditorReady(editorCtx) {
				if (!editorCtx) return

				// 保存editorCtx
				this.editorCtx = editorCtx
				// 设置编辑器内容
				this.$nextTick(() => {
					this.setContents()
				})

			},

			/**
			 * 设置编辑器内容
			 */
			setContents() {
				// 检查编辑器上下文是否存在
				if (this.editorCtx && this.formData.content) {
					// #ifdef H5
					// 如果是H5平台，则直接使用formData中的内容
					const content = this.formData.content
					// #endif

					// #ifndef H5
					// 如果不是H5平台，则需要将formData中的内容转换为编辑器所需的格式
					const content = translateInputContent(this.formData.content)
					// #endif
					// 设置编辑器内容
					this.editorCtx.setContents({
						html: content
					})
				}
			},
			// 返回上一页或跳转到首页
			navigateBack() {
				const pages = getCurrentPages()

				if (pages.length > 1) {
					// 返回上一页
					uni.navigateBack(-1)
				} else {
					// 跳转到文章列表页
					uni.redirectTo({
						url: '/pages/index/index'
					})
				}
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field("category_id,title,content,article_status,avatar").get()
					.then((res) => {
						const data = res.result.data[0]
						if (data) {
							this.formData = data
							this.$nextTick(() => {
								this.setContents()
							})

						}
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
			}
		}
	}
</script>
<style lang="scss">
	@import '@/uni_modules/uni-cms/common/style/article-detail.scss';

	.uni-container {
		background: #f8f8f8;
		padding-bottom: 66px;
		margin-top: 54px;

		.header {
			width: 950px;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			margin: 0 auto;
			z-index: 999;
			height: 60px;
			display: flex;
			align-items: center;

			.back {
				cursor: pointer;
				color: #333;
			}
		}
	}

	::v-deep .uni-forms {
		width: 35%;
		padding: 100rpx;
		border-radius: 20rpx;
	}

	::v-deep .editor-toolbar {
		z-index: 1000 !important;
	}

	::v-deep .uni-popup {
		z-index: 1001;
	}

	::v-deep .uni-drawer {
		z-index: 1002;
	}
</style>